//
//  ZLHomeController.swift
//  新浪微博
//
//  Created by 朱玉龙 on 9/22/16.
//  Copyright © 2016 朱玉龙. All rights reserved.
//

import UIKit
import SVProgressHUD


private let ZLHomeCellId = "ZLHomeCellId"
private let ZLRepostCellId = "ZLRepostCellId"
    let tipLabelH = 36
class ZLHomeController: ZLBaseTableViewController {

    private let oringinFrame: CGRect  = CGRect(x: 0, y: -tipLabelH, width: Int(screenWidth),height:tipLabelH)
    let homeNib = UINib.init(nibName: "ZLHomeCell", bundle: nil)
    let repostNib = UINib.init(nibName: "ZLRepostCell", bundle: nil)
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !login {
            let title = "关注一些人,快回到这里看看有什么惊喜"
            backView.updateInfo(title: title)
            
        }
        //数学的数据
        navigationController?.view.insertSubview(tipLabel, belowSubview: navigationController!.navigationBar)
        
        tipLabel.frame = oringinFrame
        
        //底部菊花
        self.tableView?.tableFooterView = activity
        //下拉刷新
        self.tableView.addSubview(refresh)
        refresh.isHidden = true
        refresh.reloadData = { [weak self] in
     
            self?.loadData()
        }
        //扫一扫
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(imageName: "navigationbar_pop", target: self, action: #selector(buttonClick))
        
        setupTableView()
        SVProgressHUD.show()
        loadData()
    }
    
    
    
    
    //设置界面
    func setupTableView() {
        
        
        if tableView == nil {
            
            return
        }
        
        tableView.register(homeNib, forCellReuseIdentifier: ZLHomeCellId)
        
        tableView.register(repostNib, forCellReuseIdentifier: ZLRepostCellId)
        
        tableView.separatorStyle = .none
        
        tableView.rowHeight = 360
        
        
    }
    
    //返回
    func buttonClick()  {
        
        navigationController?.pushViewController(ZLPushController(), animated: true)
    }
    
    //加载网络数据
    internal func loadData() {
        
        homeViewModel.loadData(pullUp: self.activity.isAnimating, finished: { (success,count) in
            
            if !success {
                
                SVProgressHUD.showError(withStatus: errorTitle)
                
                self.activity.stopAnimating()
                self.refresh.isHidden = false
                self.refresh.refreshStatus = .down
                self.refresh.activity.stopAnimating()
                return
            }
            
            if !self.activity.isAnimating {
                
                self.tipLabelAnimation(count: count)
            }
            
            
            SVProgressHUD.dismiss()
            self.tableView.reloadData()
            self.activity.stopAnimating()
            self.refresh.isHidden = false
            self.refresh.refreshStatus = .down
            self.refresh.activity.stopAnimating()
            self.setupTableView()
        })
        
    }
    
   // MARK: 刷新数据显示
    private func tipLabelAnimation(count: Int) {
        
        if tipLabel.isHidden == false {
            
            return
        }
        
        tipLabel.isHidden = false
        
        tipLabel.text = count == 0 ? "没有内容更新" : "\(count)条内容更新"
        
        UIView.animate(withDuration: 1, animations: {
            
            self.tipLabel.frame.origin.y = 64
            
        }) { (_) in
            
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: { 
                 self.tipLabel.frame.origin.y = CGFloat(64 - tipLabelH)
                }, completion: { (_) in
                    self.tipLabel.isHidden = true
            })
            
        }
    
    }
    
    lazy var activity: UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    //刷新数据数量提示
    lazy var refresh: ZLRefreshingControll = ZLRefreshingControll()
    
    var homeViewModel = ZLHomeViewModel()
    lazy var tipLabel: UILabel = {
        
        let label = UILabel.init(title: "", color: UIColor.white, fontSize: 14)
        label.backgroundColor = UIColor.orange
        label.textAlignment = .center
        label.isHidden = true
        return label
    }()
}




//数据源方法
extension ZLHomeController {
    
    
    
    override func  tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  homeViewModel.homeViewArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let statusMoel = self.homeViewModel.homeViewArray[indexPath.row]
        
        let cellId = setReuseableID(model: statusMoel)
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as!
        ZLHomeCell
        
        cell.statusModel = statusMoel
        
        return cell
    }
    
    
    //设置行高
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let statusMoel = self.homeViewModel.homeViewArray[indexPath.row]
        
        let cellId = setReuseableID(model: statusMoel)
        
        let cell = returnCell(cellId: cellId)
        
        let maxY =  cell.getCellMaxY(model: statusMoel)
        
        return maxY
    }
    
    //上啦刷新
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        
        
        if indexPath.row == homeViewModel.homeViewArray.count - 2 {
            
            if self.activity.isAnimating == true {
                
                return
            }
            
            self.activity.startAnimating()
            
            self.loadData()
            
        }
        
    }
    
    //MARK: 下拉刷新
    
    

    
    //返回可重用的cell
    
    func returnCell(cellId: String) ->ZLHomeCell {
        
        let nibName = cellId == ZLHomeCellId ? "ZLHomeCell" : "ZLRepostCell"
        
        return UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil).last as! ZLHomeCell
        
    }
    
    
    
    
    
    
    //设置从用表示
    func setReuseableID(model: ZLStatusViewModel) -> String {
        
        if model.status?.retweeted_status == nil {
            
            return ZLHomeCellId
        }
        
        return  ZLRepostCellId
        
    }
    
}

